package com.wswy.wzcx.ui.user

import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.util.Log
import android.view.animation.AnimationUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.module.base.ApiCallback
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.module.base.invisible
import com.wswy.wzcx.module.base.onResult
import com.wswy.wzcx.module.validator.ValidatorResult
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.other.TextWatcherIMPL
import com.wswy.wzcx.utils.StringUtils
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.subscribers.ResourceSubscriber
import kotlinx.android.synthetic.main.fragment_phone_verify.*
import kotlinx.android.synthetic.main.layout_login_service.*
import java.util.concurrent.TimeUnit

/**
 * 手机号验证
 */
class PhoneVerifyFragment : BaseVerifyFragment() {

    companion object {
        private const val TAG = "PhoneVerifyFragment"
    }

    private var smsCodeDisposable: ResourceSubscriber<Long>? = null


    override fun getContentLayoutId(): Int {
        return R.layout.fragment_phone_verify
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        loginHolderViewModel=provideViewModelFromActivity(LoginHolderViewModel::class.java)


        tv_msg_hint.text = getString(R.string.sms_msg_hint,StringUtils.hidePhone(loginHolderViewModel.stepState.phone))

        et_phone_code.addTextChangedListener(object :TextWatcherIMPL(){
            override fun afterTextChanged(s: Editable?) {
                super.afterTextChanged(s)

                checkInput()
            }
        })

        //获取验证码
        tv_fetch_code.setOnClickListener {

            startGVerify()

            //统计
            when(loginHolderViewModel.stepState.type){
                LoginHolderViewModel.TYPE_REG,LoginHolderViewModel.TYPE_WECHAT_BIND-> {
                    sendClickEvent(StatisticsId.u_zc_resend)
                }
                LoginHolderViewModel.TYPE_FORGET_PWD -> {
                    sendClickEvent(StatisticsId.u_dl_wjmm_resend)
                }
            }

        }
        //服务协议
        tv_service_protocol.highlightColor = Color.TRANSPARENT
        tv_service_protocol.movementMethod = LinkMovementMethod.getInstance()
        tv_service_protocol.text = LoginHelper.getServiceString(requireContext())

        //隐私协议
        cb_agree_protocol.setOnCheckedChangeListener { _, isChecked ->
            checkInput()
        }

        //点击下一步
        btn_next_step.setOnClickListener {
            if (!cb_agree_protocol.isChecked){
                val shake = AnimationUtils.loadAnimation(context,R.anim.anim_input)
                ll_service_layout.startAnimation(shake)
                ToastUtils.showText("请勾选同意《用户协议》及《隐私政策》")
                return@setOnClickListener
            }
            val uPhone = loginHolderViewModel.stepState.phone

            val code = et_phone_code.text?.toString()
            if (uPhone.isNullOrEmpty() || code.isNullOrEmpty()){
                ToastUtils.showText("系统内部错误，请返回上一步")
                return@setOnClickListener
            }

            //统计
            when(loginHolderViewModel.stepState.type){
                LoginHolderViewModel.TYPE_REG-> {
                    sendClickEvent(StatisticsId.u_zc_tj_yzm)
                }

                LoginHolderViewModel.TYPE_WECHAT_BIND -> {
                    sendClickEvent(StatisticsId.u_wechat_tj_yzm)
                }

                LoginHolderViewModel.TYPE_FORGET_PWD -> {
                    sendClickEvent(StatisticsId.u_dl_wjmm_tj_yzm)
                }
            }

            loginHolderViewModel.stepState.smsCode = code


            loginHolderViewModel.addRun(Api.get().phoneSmsCodeValid(uPhone,code).onResult({

                if (!isHidden){

                    if (it?.ticket.isNullOrEmpty()){
                        ToastUtils.showText("校验失败")
                    }else {
                        //校验成功

                        loginHolderViewModel.stepState.ticket = it?.ticket


                        //loginHolderViewModel.

                        if (loginHolderViewModel.stepState.type == LoginHolderViewModel.TYPE_WECHAT_BIND){
                            doWxBind()
                        }else{
                            loginHolderViewModel.clickEvent(LoginHolderViewModel.CLICK_SMS_CODE_NEXT_STEP)
                        }

                    }
                }

            },{

                if (!isHidden){
                    ApiCallback.toastErrorMsg(it)
                }
            }))

            //
        }


        if (loginHolderViewModel.oneKeyLogin){
            ll_service_layout.invisible()
            cb_agree_protocol.isChecked = true
        }

        KeyboardUtils.showSoftInput(et_phone_code)

        startTrack()

    }

    override fun lockLoad() {
        super.lockLoad()
//        et_phone_code.isEnabled = false
//        tv_fetch_code.isClickable = false
//        btn_next_step.isClickable = false
    }

    override fun unlockLoad() {
        super.unlockLoad()

//        et_phone_code.isEnabled = true
//        tv_fetch_code.isClickable = true
//        btn_next_step.isClickable = true

    }

    override fun onGVerifySuccess(ticket: ValidatorResult) {
        super.onGVerifySuccess(ticket)

        val phone = loginHolderViewModel.stepState.phone?:return

        loginHolderViewModel.sendSMSVerify(phone, ticket)
    }

    override fun onSending() {
        super.onSending()
        lockLoad()
    }

    override fun onSendSuccess() {
        super.onSendSuccess()
        unlockLoad()
        ToastUtils.showText("验证码已发送")
        startTrack()
    }

    override fun onSendFail(msg: String?) {
        super.onSendFail(msg)
        unlockLoad()
        ToastUtils.showText(msg)
    }

    //微信绑定
    private fun doWxBind(){
        val state = loginHolderViewModel.stepState;

        Api.get().wechatBind(state.wechatCode,state.phone,state.ticket).onResult({

            it?.run {

                sendClickEvent(StatisticsId.u_wechat_done)

                loginHolderViewModel.setUserLogined(this)
            }
            //loginHolderViewModel.clickEvent(LoginHolderViewModel.CLICK_WX_BIND_SUCCESS)

        },{

            sendClickEvent(StatisticsId.u_wechat_fail)

            ApiCallback.toastErrorMsg(it)
        })

    }

    private fun checkInput(){
        val codeValue = et_phone_code.text

        btn_next_step.isEnabled = !TextUtils.isEmpty(codeValue) && codeValue?.length?:0 >=4
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)

        if (hidden){
            cancelTrack()

            KeyboardUtils.hideSoftInput(et_phone_code)

        }else{
            resetViews()

            KeyboardUtils.showSoftInput(et_phone_code)
        }
        Log.e(TAG, "onHiddenChanged --> "+hidden);

    }

    private fun resetViews(){

        tv_msg_hint.text = getString(R.string.sms_msg_hint,StringUtils.hidePhone(loginHolderViewModel.stepState.phone))

        loginHolderViewModel.stepState.smsCode?.let {
            et_phone_code.setText(it)
            et_phone_code.setSelection(it.length)
        }?:kotlin.run {
            startTrack()
        }

    }

    private fun startTrack(){

        cancelTrack()

        smsCodeDisposable = object :ResourceSubscriber<Long>(){
            override fun onComplete() {
                tv_fetch_code.isClickable = true
                tv_fetch_code.isEnabled = true
                tv_fetch_code.setText(R.string.fetch_ver_code)
            }

            override fun onNext(t: Long) {

                tv_fetch_code.isEnabled = false
                tv_fetch_code.isClickable = false
                tv_fetch_code.text = getString(R.string.captcha_timer,59-t)

            }

            override fun onError(t: Throwable?) {
                ToastUtils.showError(t)
            }

        }


        Flowable.intervalRange(0, 59, 0, 1, TimeUnit.SECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(smsCodeDisposable)
    }

    private fun cancelTrack(){
        smsCodeDisposable?.dispose()
        smsCodeDisposable = null
    }

    override fun onDestroyView() {
        super.onDestroyView()
        cancelTrack()
    }

    override fun onDestroy() {
        super.onDestroy()
        cancelTrack()
    }

}